package com.devin.avatar.common.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.devin.avatar.common.util.JsonUtil;

public abstract class BaseController {
    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 客户端返回JSON字符串
     * 
     * @param response
     * @param object
     * @return
     */
    protected String renderString(HttpServletResponse response, Object object) {
	String str = JsonUtil.toJsonString(object);
	return renderString(response, str, "application/json");
    }

    /**
     * 客户端返回字符串
     * 
     * @param response
     * @param string
     * @return
     */
    protected String renderString(HttpServletResponse response, String string, String type) {
	try {
	    response.reset();
	    response.setContentType(type);
	    response.setCharacterEncoding("utf-8");
	    response.getWriter().print(string);
	    return null;
	} catch (IOException e) {
	    return null;
	}
    }

    /**
     * 添加Model消息
     * 
     * @param message
     */
    protected void addMessage(Model model, String... messages) {
	StringBuilder sb = new StringBuilder();
	for (String message : messages) {
	    sb.append(message).append(messages.length > 1 ? "<br/>" : "");
	}
	model.addAttribute("message", sb.toString());
    }

    /**
     * 添加Flash消息
     * 
     * @param message
     */
    protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
	StringBuilder sb = new StringBuilder();
	for (String message : messages) {
	    sb.append(message).append(messages.length > 1 ? "<br/>" : "");
	}
	redirectAttributes.addFlashAttribute("message", sb.toString());
    }
}
